# 这是一个示例 Python 脚本。

# 按 Ctrl+F5 执行或将其替换为您的代码。
# 按 双击 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。


# -*- coding: utf-8 -*-
import urllib
from datetime import date
from time import sleep

import wx
import wx.xrc
import qrcode
import serial
import serial.tools.list_ports

from encode import encrypt_oracle, decrypt_oralce
from mythread import ThreadTime, ThreadSerial


class MyFrame2(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition,
                          size=wx.Size(836, 637), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)

        self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)

        sbSizer2 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u"二维码"), wx.VERTICAL)

        bSizer1 = wx.BoxSizer(wx.HORIZONTAL)

        bSizer2 = wx.BoxSizer(wx.VERTICAL)

        bSizer1.Add(bSizer2, 1, wx.EXPAND, 5)

        self.m_textCtrl5 = wx.TextCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,
                                       wx.DefaultSize, style=wx.TE_MULTILINE | wx.TE_RICH2)
        bSizer1.Add(self.m_textCtrl5, 1, wx.ALL | wx.EXPAND, 5)

        self.m_bitmap4 = wx.StaticBitmap(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.Bitmap(
            u"rcode.png", wx.BITMAP_TYPE_ANY),
                                         wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_bitmap4.SetMinSize(wx.Size(400, 400))

        bSizer1.Add(self.m_bitmap4, 1, wx.ALL | wx.EXPAND, 5)

        sbSizer2.Add(bSizer1, 1, wx.EXPAND, 5)

        bSizer4 = wx.BoxSizer(wx.HORIZONTAL)

        self.m_staticText1 = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u"选择Android串口", wx.DefaultPosition,
                                           wx.DefaultSize, 0)
        self.m_staticText1.Wrap(-1)

        bSizer4.Add(self.m_staticText1, 0, wx.ALL, 5)

        m_choice1Choices = self.serial()  # 获取串口
        self.m_choice1 = wx.Choice(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
                                   m_choice1Choices, 0)
        self.m_choice1.SetSelection(0)
        bSizer4.Add(self.m_choice1, 0, wx.ALL, 5)

        self.m_button2 = wx.Button(sbSizer2.GetStaticBox(), wx.ID_ANY, u"手动打印二维码", wx.DefaultPosition, wx.DefaultSize,
                                   0)
        # self.m_button2.Disable()
        bSizer4.Add(self.m_button2, 0, wx.ALL, 5)

        sbSizer2.Add(bSizer4, 0, 0, 5)

        bSizer5 = wx.BoxSizer(wx.HORIZONTAL)

        self.m_staticText2 = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u"选择打印机串口", wx.DefaultPosition,
                                           wx.DefaultSize, 0)
        self.m_staticText2.Wrap(-1)

        bSizer5.Add(self.m_staticText2, 0, wx.ALL, 5)

        bSizer5.Add((11, 0), 0, 0, 1)

        m_choice2Choices = self.serial()  # 获取串口
        self.m_choice2 = wx.Choice(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
                                   m_choice2Choices, 0)
        self.m_choice2.SetSelection(0)
        bSizer5.Add(self.m_choice2, 0, wx.ALL, 5)

        sbSizer2.Add(bSizer5, 0, 0, 5)

        self.SetSizer(sbSizer2)
        self.Layout()

        self.Centre(wx.BOTH)
        self.m_button2.Bind(wx.EVT_BUTTON, self.on_click)
        self.m_choice1.Bind(wx.EVT_CHOICE, self.on_choice)
        self.m_choice2.Bind(wx.EVT_CHOICE, self.on_choice_print)
        # self.m_choice1.Bind(wx.EVT_UPDATE_UI, self.update_ui)

        # # 获取串口
        self.serial_print = None

    def __del__(self):
        pass

    # Virtual event handlers, overide them in your derived class
    def update_ui(self, event):
        event.Skip()
        m_serial = self.serial()
        if len(m_serial) > 0:
            for m in m_serial:
                m_int = self.m_choice1.FindString(m)
                print(m_int, m)
                if m_int == wx.NOT_FOUND:
                    self.m_choice1.Append(m)
                    self.m_choice1.Select(0)
                    # print(self.m_choice1.GetCount())
                    # self.m_choice1.SetString(self.m_choice1.GetCount() - 1, m)
            self.Update()

    # Virtual event handlers, overide them in your derived class
    def on_click(self, event):
        event.Skip()

        lines = self.m_textCtrl5.GetNumberOfLines()
        str = ''
        if 0:
            for i in range(lines):
                str = str + self.m_textCtrl5.GetLineText(i) + '\r\n'

        if 1:
            CPUID = self.m_textCtrl5.GetLineText(0)
            MAC_LAN = self.m_textCtrl5.GetLineText(1)
            MAC_WLAN = self.m_textCtrl5.GetLineText(2)
            # str = CPUID + MAC_LAN + MAC_WLAN

        self.print_message(CPUID, MAC_LAN, MAC_WLAN)

    def write_rcode_bitmap(self, str):
        # 调用qrcode的make()方法传入url或者想要展示的内容
        img = qrcode.make(str)
        # 写入文件
        with open('rcode.png', 'wb') as f:
            img.save(f)
        bit_map = wx.Bitmap(u"rcode.png")
        bit_map.SetSize(self.m_bitmap4.GetSize())
        self.m_bitmap4.SetBitmap(bit_map)

        # self.serial_print.write(self.print_rcode(strs).encode())  # 写数据

    def print_message(self, CPUID, MAC_LAN, MAC_WLAN):
        if self.serial_print is not None:
            strs = self.print_rcode(CPUID, MAC_LAN, MAC_WLAN)
            # result = self.serial_print.write('SIZE 96 mm,20 mm\r\nGAP 2 mm\r\nCLS\r\nSPEED 1.5\r\nDENSITY 15\r\nQRCODE 800,30,L,4,A,0,"123\r\n"\r\nTEXT 960,140,"2",0,1,1,"2021-11-16"\r\nPRINT 1\r\n'.encode())  # 写数据
            result = self.serial_print.write(strs.encode())
            print(result)
        else:
            self.print_rcode(CPUID, MAC_LAN, MAC_WLAN)

    def print_rcode(self, CPUID, MAC_LAN, MAC_WLAN):
        _batch_no = str(date.today())  # 当前日期
        batch_no = _batch_no.replace('-', '')
        cpuid = CPUID
        mac_lan = MAC_LAN
        mac_wlan = MAC_WLAN

        text = 'PRODUCT_ID:MK-3\n' + cpuid + '\n' + mac_lan + '\n' + mac_wlan + '\nAPP_ID:1000\nBATCH_NO:' + batch_no
        entrypted_text = encrypt_oracle(text)
        print('加密：', entrypted_text)
        print('解密：', decrypt_oralce(entrypted_text))
        entrypted_text = urllib.parse.quote(entrypted_text)  # urlencode编码
        print('urlencode编码：', entrypted_text)

        url = 'https://qrcode-h5.jsunet.cn/app/default?k=' + entrypted_text + '&appId=1000&SN=' + cpuid.replace('\n',
                                                                                                                '').replace(
            'CPUID:', '') + '&productId=MK-3'
        # url = '12346'
        print('url: ', url)
        self.write_rcode_bitmap(url)

        strPinterTmp = "SIZE 65 mm,20 mm\r\nGAP 2 mm\r\nCLS\r\nSPEED 1.5\r\nDENSITY 15\r\n"
        strPinterTmp += 'QRCODE 530,45,L,3,M,0,'
        # strPinterTmp += '"' + CPUID +'\r\n' + MAC_LAN +'\r\n' + MAC_WLAN + '"' + '\r\n'
        strPinterTmp += '"' + url + '"' + "\r\n"
        # 打印字符串
        strPinterTmp += 'TEXT 60,45,"2",0,1,1,' + '"' + CPUID + '"' + '\r\n'
        strPinterTmp += 'TEXT 60,65,"2",0,1,1,' + '"' + MAC_LAN + '"' + '\r\n'
        strPinterTmp += 'TEXT 60,85,"2",0,1,1,' + '"' + MAC_WLAN + '"' + '\r\n'
        # 打印字符串
        strPinterTmp += 'TEXT 60,165,"2",0,1,1,' + '"' + CPUID + '"' + '\r\n'
        strPinterTmp += 'TEXT 60,185,"2",0,1,1,' + '"' + MAC_LAN + '"' + '\r\n'
        strPinterTmp += 'TEXT 60,205,"2",0,1,1,' + '"' + MAC_WLAN + '"' + '\r\n'

        strPinterTmp += "PRINT 1\r\n"
        print(strPinterTmp)
        return strPinterTmp

    def on_choice(self, event):
        event.Skip()
        print('EvtChoice: %s\n' % event.GetString())
        self.com = event.GetString()

        serial = self.open_port(event.GetString(), 115200, None)
        if serial is not None:
            m_thread = ThreadTime(self, serial, event.GetString())
            m_thread.start()

    def on_choice_print(self, event):
        event.Skip()
        print('EvtChoice: %s\n' % event.GetString())
        self.com = event.GetString()

        self.serial_print = self.open_port(event.GetString(), 9600, None)
        if serial is None:
            dlg = wx.MessageDialog(self, '打开打印机串口失败',
                                   '警报',
                                   wx.OK | wx.ICON_INFORMATION
                                   # wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
                                   )
            dlg.ShowModal()
            dlg.Destroy()

    def serial(self):
        # self.log.WriteText('EvtChoice: %s\n' % event.GetString())
        # self.ch.Append("A new item")
        print('seial')
        m_list = []
        port_list = list(serial.tools.list_ports.comports())
        # print(port_list)
        if len(port_list) == 0:
            print('无可用串口')
            return m_list
        else:
            for i in range(0, len(port_list)):
                print(port_list[i])
                # self.m_choice1.SetString(1, port_list[i][1])
                m_list.append(port_list[i][0])
            return m_list

    # 打开串口
    # 端口，GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
    # 波特率，标准值之一：50,75,110,134,150,10,300,10,1200,1800,2400,4800,9600,19200,38400,57600,115200
    # 超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）
    def open_port(self, port, bps, timeout):
        ser = None
        try:
            # 打开串口，并得到串口对象
            ser = serial.Serial(port, bps, timeout=timeout)
        except Exception as e:
            print("---异常---：", e)
        return ser

    # 写数据
    def write(self, ser):
        # 十六进制的发送
        result = ser.write(b'\x50\x03\x00\x34\x00\x01\xc8\x45')  # 写数据
        return result

    # 读数代码本体实现
    def read(self, serial):
        while True:
            data = serial.read_all()
            print(data)
            sleep(1)

    # def print_rcode(self, str1, str2, str3):
    #     strPinterTmp = "SIZE 96 mm,20 mm\r\nGAP 2 mm\r\nCLS\r\nSPEED 1.5\r\nDENSITY 15\r\n";
    #     strPinterTmp += "QRCODE 50,30,L,4,A,0,";
    #     strPinterTmp += str1;
    #     strPinterTmp += "\r\n";  # 字符串一拼接完成
    #
    #     strPinterTmp += "QRCODE 420,30,L,4,A,0,";
    #     strPinterTmp += str2;
    #     strPinterTmp += "\r\n";  # 字符串二拼接完成
    #
    #     strPinterTmp += "QRCODE 800,30,L,4,A,0,";
    #     strPinterTmp += (str3);
    #     strPinterTmp += "\r\n";  # 字符串三拼接完成
    #     strPinterTmp += "\r\n" + "PRINT 1\r\n";
    #     # SerialPortManager.sendToPort(mSerialport2, strPinterTmp.getBytes());
    #     # return strPinterTmp;
    #     # ser = self.open_port(load_dict['serial'], 115200, 5)


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame2(None)
    frame.Show(True)
    app.MainLoop()
